package com.tutu.flow.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tutu.common.GlobalConstants;
import com.tutu.common.GlobalConstants.ISessionMessageSetting;
import com.tutu.common.util.DatatablesJson;
import com.tutu.common.util.JsonReturnObject;
import com.tutu.common.util.LogAction;
import com.tutu.common.util.SysAuditModelType;
import com.tutu.flow.entity.BpmForm;
import com.tutu.flow.service.IBpmFormService;
import com.tutu.user.entity.SysUserGroupMebers;
import com.tutu.user.service.ISysUserGroupMebersService;

@Controller
@RequestMapping("/flow")
@LogAction(ownermodel=SysAuditModelType.PROCESS_MANAGEMENT)
public class BusinessProcessAction {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private ISysUserGroupMebersService sysUserGroupMebersService;
	@Resource
	private IBpmFormService bpmFormService;
	
	@Resource
	private RuntimeService runtimeService;
	@Resource
	private TaskService taskService;
	
	@RequestMapping("/companyRegistry")
	public String goCompanyRegistry(){
		return "flow/companyRegistry";
	}
	
	@RequestMapping("/otherBusiness")
	public String otherBusiness(Model model){
		try {
			String businessNo = this.bpmFormService.getNewBusinessNo();
			model.addAttribute("businessNo", businessNo);
		} catch (Exception e) {
			logger.error("获取最新业务编号", e);
		}
		return "flow/otherBusiness";
	}
	
	@RequestMapping("/getOtherBusiness")
	public String getOtherBusiness(Model model,@RequestParam String taskId){
		BpmForm bpmForm = taskService.getVariable(taskId, GlobalConstants.FLOW_FROM_VAR, BpmForm.class);
		bpmForm.setTaskId(taskId);
		model.addAttribute("bpmForm", bpmForm);
		return "flow/getOtherBusiness";
	}
	
	@RequestMapping("/saveOtherBusiness")
	@LogAction(description="提交其它业务流程申请")
	public String saveOtherBusiness(HttpSession session, @ModelAttribute("bpmFrom") BpmForm bpmForm){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "其它业务申请失败", "其它业务申请成功");
		bpmForm.setAliveFlag(GlobalConstants.FLAG_DISENABLE);
		bpmForm.setCreator(GlobalConstants.getCurrentUser().getUserId());
		bpmForm.setCreatorName(GlobalConstants.getCurrentUser().getUserName());
		bpmForm.setCreateTime(Calendar.getInstance().getTime());
		
		try {
			bpmFormService.saveProcessInstance(BpmForm.OTHER_BUSINESS, bpmForm);
			sessionMessageSetting.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("其它业务流程申请", e);
		}
		return "redirect:/flow/otherBusiness.do";
	}
	
	@RequestMapping("/myTasks")
	public String myTasks(){
		return "flow/myTasks";
	}
	
	@RequestMapping("/getMyTasks")
	@ResponseBody
	public JsonReturnObject<DatatablesJson<BpmForm>> getMyTasks(@RequestParam(required=false) String processDefinitionKey, @RequestParam String sEcho, @RequestParam int iDisplayStart,@RequestParam int iDisplayLength,@RequestParam(required=false) String sSearch){
		JsonReturnObject<DatatablesJson<BpmForm>> jsonReturnObject = new JsonReturnObject<DatatablesJson<BpmForm>>(false,"获取表单信息失败");
		SysUserGroupMebers sysUserGroupMebers = new SysUserGroupMebers();
		sysUserGroupMebers.setUserId(GlobalConstants.getCurrentUser().getUserId());
		sysUserGroupMebers.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		List<SysUserGroupMebers> sysUserGroupMebersList = this.sysUserGroupMebersService.getSysUserGroupMebers(sysUserGroupMebers);
		List<String> groupIds = new ArrayList<String>();
		for(SysUserGroupMebers sysGroupMebers : sysUserGroupMebersList){
			groupIds.add(sysGroupMebers.getSysUserGroup().getGroupCode());
		}
		TaskQuery taskQuery = this.taskService.createTaskQuery();
		if(StringUtils.isNotBlank(processDefinitionKey)){
			taskQuery.processDefinitionKey(processDefinitionKey);
		}
		List<Task> tasks = taskQuery.or().taskCandidateGroupIn(groupIds).taskAssignee(GlobalConstants.getCurrentUser().getLoginName()).orderByDueDateNullsLast().desc().listPage(iDisplayStart, iDisplayLength);
		Long total = Long.valueOf(taskQuery.count());
		List<BpmForm> bpmForms = new ArrayList<BpmForm>();
		for(Task task : tasks){
			BpmForm bpmForm = taskService.getVariable(task.getId(), GlobalConstants.FLOW_FROM_VAR, BpmForm.class);
			bpmForm.setTaskId(task.getId());
			bpmForms.add(bpmForm);
		}
		DatatablesJson<BpmForm> datatablesJson = new DatatablesJson<BpmForm>();
		datatablesJson.setEcho(sEcho);
		datatablesJson.setTotalRecords(total.intValue());
		datatablesJson.setTotalDisplayRecords(total.intValue());
		datatablesJson.setData(bpmForms);
		jsonReturnObject.setIsSuccess(true);
		jsonReturnObject.setReturnObject(datatablesJson);
		return jsonReturnObject;
	}
	
	@RequestMapping("/myApply")
	public String myApply(){
		return "";
	}
	
	@RequestMapping("/myAction")
	public String myAction(){
		return "";
	}
	
	@RequestMapping("/myDealOver")
	public String myDealOver(){
		return "";
	}
}
